<template>
  <el-form
    :model="ruleForm"
    :rules="rules"
    ref="ruleForm"
    status-icon
    label-width="100px"
    class="demo-ruleForm"
  >
    <el-form-item label="昵称" prop="name">
      <el-input type="text" v-model="ruleForm.name" auto-complete="off"></el-input>
    </el-form-item>
    <el-form-item label="账号" prop="username">
      <el-input type="text" v-model="ruleForm.username" auto-complete="off"></el-input>
    </el-form-item>
    <el-form-item label="密码" prop="password">
      <el-input type="password" v-model="ruleForm.password" auto-complete="off"></el-input>
    </el-form-item>

    <el-form-item label="确认密码" prop="checkPass">
      <el-input type="password" v-model="ruleForm.checkPass" auto-complete="off"></el-input>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="submitForm('ruleForm')">注册</el-button>
      <el-button @click="resetForm('ruleForm')">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
export default {
  props: ["url"],
  data() {
    var validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.ruleForm.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      ruleForm: {
        name: "",
        username: "",
        password: "",
        checkPass: ""
      },
      rules: {
        name: [
          { required: true, message: "请输入用户昵称", trigger: "blur" },
          { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" }
        ],
        username: [
          { required: true, message: "请输入账号", trigger: "blur" },
          { min: 5, max: 20, message: "长度在 5 到 20 个字符", trigger: "blur" }
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        checkPass: [
          { required: true, validator: validatePass2, trigger: "blur" }
        ]
      }
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (!valid) {
          this.$notify.error({
            title: "错误",
            message: "表单格式错误"
          });
          return false;
        } else {
          this.registerPost();
          return true;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    async registerPost() {
      try {
        let { status, data } = await this.$axios.post(this.url, this.ruleForm);
        this.$notify.success({
          title: "成功",
          message:"3秒内进行登录页面跳转"
        });
        setTimeout(()=>{
          this.$router.push("/login")
        },3000)
      } catch (error) {
          let {status,response:{data:{error_msg}}} = error;
          this.$notify.error({
            title: "错误",
            message:error_msg        
          });
      }
    }
  }
};
</script>

<style scoped>
</style>